package config

import (
	"errors"
	"strings"
)

// Service's custom configuration which is loaded from the configuration.toml
type ServiceConfig struct {
	MqttClientConfig MQTTConfig
}

type MQTTConfig struct {
	// BrokerAddress should be set to the complete broker address i.e. mqtts://mosquitto:8883/mybroker
	BrokerAddress string
	// ClientId to connect with the broker with.
	ClientId string
	// The name of the path in secret provider to retrieve your secrets
	SecretPath string
	// AutoReconnect indicated whether or not to retry connection if disconnected
	AutoReconnect bool
	// KeepAlive is the interval duration between client sending keepalive ping to broker
	KeepAlive string
	// ConnectTimeout is the duration for timing out on connecting to the broker
	ConnectTimeout string

	// QoS for MQTT Connection
	QoS byte
	// Retain setting for MQTT Connection
	Retain bool
	// SkipCertVerify
	SkipCertVerify bool
	// AuthMode indicates what to use when connecting to the broker. Options are "none", "cacert" , "usernamepassword", "clientcert".
	// If a CA Cert exists in the SecretPath then it will be used for all modes except "none".
	AuthMode string

	// iotkit信息--------begin
	ProductKey string
	//
	DeviceName string

	Model string
	// iotkit信息--------end
}

// UpdateFromRaw updates the service's full configuration from raw data received from
// the Configuration Provider. Can just be a dummy 'return true' if never using the Configuration Provider
func (c *ServiceConfig) UpdateFromRaw(rawConfig interface{}) bool {
	configuration, ok := rawConfig.(*ServiceConfig)
	if !ok {
		return false //errors.New("unable to cast raw config to type 'ServiceConfig'")
	}

	*c = *configuration

	return true
}

func (c *ServiceConfig) Validate() error {
	if len(strings.TrimSpace(c.MqttClientConfig.BrokerAddress)) == 0 {
		return errors.New("Configuration missing value for MqttSecretConfig.BrokerAddress")
	}

	if len(strings.TrimSpace(c.MqttClientConfig.ClientId)) == 0 {
		return errors.New("Configuration missing value for MqttSecretConfig.ClientId")
	}

	if len(strings.TrimSpace(c.MqttClientConfig.AuthMode)) == 0 {
		return errors.New("Configuration missing value for MqttSecretConfig.AuthMode")
	}

	if len(strings.TrimSpace(c.MqttClientConfig.ProductKey)) == 0 {
		return errors.New("Configuration missing value for MqttSecretConfig.ProductKey")

	}

	if len(strings.TrimSpace(c.MqttClientConfig.DeviceName)) == 0 {
		return errors.New("Configuration missing value for MqttSecretConfig.DeviceName")

	}
	if len(strings.TrimSpace(c.MqttClientConfig.Model)) == 0 {
		return errors.New("Configuration missing value for MqttSecretConfig.Model")

	}

	return nil
}
